import React, { Component } from 'react'
import Header from './components/header/Header'
import List from './components/list/List'

export default class App extends Component {
  state = {
    curType:JSON.parse(localStorage.getItem('curType')) || 0,
    list:JSON.parse(localStorage.getItem('list')) || []
  }
  onAdd = (text) => {
    console.log(text)
    this.setState({
      list:[...this.state.list,{
        id:Date.now(),
        checked:false,
        text
      }]
    })
  }

  del = (id) => {
    const list = [...this.state.list]
    const List = list.filter(v=>v.id !== id)
    this.setState({
      list:List
    })
  }
  onChangeChecked = id => {
    const list = [...this.state.list]
    const index = list.findIndex(item => item.id === id)
    list[index].checked = !list[index].checked
    this.setState({
      list
    })
  }
  ChangeType = (type) => {
    this.setState({
      curType:type
    })
  }

  filterList = () => {
    if(this.state.curType === 1) {
      return this.state.list.filter(v => !v.checked)
    }else if(this.state.curType === 2) {
      return this.state.list.filter(v => v.checked)
    }
    return this.state.list
  } 

  componentDidUpdate() {
    localStorage.setItem('list',JSON.stringify(this.state.list))
    localStorage.setItem('curType',this.state.curType)
  }


  render() {
    const curList = this.filterList()
    return (
      <div className='bg'>
       <div className='content'>
        <Header onSubmit={this.onAdd} total={this.state.list.length} curType={this.state.curType} onChangeType={this.ChangeType}/>
        <List list={curList} onDel={this.del} onChangeChecked={this.onChangeChecked}/>
       </div>
      </div>
    )
  }
}
